#!/usr/bin/env python
 
import tornado.httpserver
import tornado.ioloop
import tornado.options 
import tornado.database
import os 

from tornado.options import define, options
from apps.common import BaseHandler


define("port", default=8080, type=int) 

define("mysql_host", default="127.0.0.1:3306")
define("mysql_database", default="promise")
define("mysql_user", default="root")
define("mysql_password", default="123456")


def build_handlers():
    def with_prefix(res, handlers, prefix = ''):
        for p in handlers:
            if p[0] == '':
                p_new = (r'%s'%prefix, p[1])
            else:
                p_new = (r'%s/%s'%(prefix,p[0]), p[1])
            res.append(p_new)
        
    res = []
    #1) quote
    from apps.quote import handlers
    with_prefix(res, handlers)
    
    #2) zbus
    from apps.zbus import handlers
    with_prefix(res, handlers, '/zbus')
    
    res.append((r'/', MainHandler))
    
    return res

class Application(tornado.web.Application):
    def __init__(self):
        handlers =  build_handlers()
        import socket
        ips = [ip for ip in socket.gethostbyname_ex(socket.gethostname())[2] if not ip.startswith("127.")][:1]
        
        settings = dict(
            debug = True,
            cookie_secret="32oETzKXQAGaYdkL5gEmGeJJFuYh7EQnp2XdTP1o/Vo=",
            static_path = os.path.join(os.path.dirname(__file__), 'static'),
            template_path = os.path.join(os.path.dirname(__file__),'template'),
            static_prefix = 'http://%s:%d/static'%(ips[0],options.port)
        )
        tornado.web.Application.__init__(self, handlers, **settings)
        
        self.db = tornado.database.Connection(
                host = options.mysql_host,database = options.mysql_database,
                user = options.mysql_user,password = options.mysql_password)
        
        

 
class MainHandler(BaseHandler): 
    def get(self):  
        self.render('index.html')

 
def main():
    tornado.options.parse_command_line()
    http_server = tornado.httpserver.HTTPServer(Application())
    http_server.listen(options.port)
    tornado.ioloop.IOLoop.instance().start()


if __name__ == "__main__":
    main()